import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from '../action/actionTypes'

let initState = { //用户信息初始状态
  isLoading:false,  
  isLogin:false,
  userInfo:null
}

let uInfo = localStorage.getItem('userInfo') //尝试从本地存储提取用户信息
// console.log(uInfo);
if(uInfo){ //如果本地存储有内容
  initState.isLogin = true
  initState.userInfo = JSON.parse(uInfo)
}

export const userReducer = (state=initState,action)=>{
  switch (action.type) {
    case LOGIN_START:  //用户触发登录按钮
      state.isLoading = true
      console.log('开始登录了',state);
      return { ...state }
    case LOGIN_SUCCESS:  //登录成功
      state.isLoading = false   //关闭loading窗
      state.isLogin = true     //记录成功状态
      state.userInfo = action.payload  //记录用户信息
      localStorage.setItem('userInfo', JSON.stringify(action.payload)) //向本地存储记录用户信息
      return { ...state }
    case LOGIN_FAIL:  //用户触发登录按钮
      state.isLoading = false   //关闭loading窗
      state.isLogin = false     //记录失败状态
      state.userInfo = null  //清除用户信息
      localStorage.removeItem('userInfo')  //清除本地用户信息
      return { ...state }
    default:
      return state
  }
}